<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Evan
 * Date: 12-10-11
 * Time: 下午1:08
 * To change this template use File | Settings | File Templates.
 */
class Jwawa_Tree_Builder
{
    private static function addToTree($src_node, $target_node)
    {
        $exist = false;
        $sub_node = null;
        foreach ($src_node->getChildren() as $sub_node) {
            if ($target_node->getId() == $sub_node->getId()) {
                $exist = true;
                break;
            }
        }

        if ($exist) {
            return $sub_node;
        } else {
            $children = $src_node->getChildren();
            for ($i = 0; $i < count($children); $i++) {
                if ($target_node->getSeqNbr() <= $src_node->children[$i]->getSeqNbr()) {
                    break;
                }
            }

            array_splice($src_node->getChildren(), $i, 0, array($target_node));

            return $target_node;
        }
    }

    public function buidTree($root, $node_hash){
        foreach($node_hash as $node){
            $node_id_list = explode('.', $node->getHierarchyFlag(), -1);

            $current_node = $root;
            foreach($node_id_list as $node_id){
                $node = $node_hash[$node_id];
                if(!isset($node_id)){
                    throw new Exception("not found tree node");
                }
                $current_node = self::addToTree($current_node, $node);
            }
        }

        return $root;
    }
}
